<template>
  <ul>
    <li v-for="item in list" :key="item.id">
      <span>{{ item.title }}</span>
      <span>{{ item.content }}</span>
      <button @click="updateItem(item)"style=" margin-left: 80px;">修改</button>
      <button @click="deleteItem(item.id)" style="">删除</button>
    </li>
    <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
      <el-form :model="form">
        <el-form-item label="标题">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="是否公开">
          <el-switch v-model="form.delivery" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">更改</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </ul>
</template>

<script setup lang="ts">
import http from "../utils/http.js";
import { ref, reactive } from "vue";
let list = ref<any>([]);
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = reactive({
  id: 0,
  title: "",
  content: "",
  delivery: false,
});
function loadlist() {
  http({
    method: "get",
    url: "/posts",
  }).then((res: any) => {
    // console.log(res)
    list.value = res.data;
  });
}
loadlist();
function updateItem(item: any) {
  dialogFormVisible.value = true;
  form.id = item.id;
  form.title = item.title;
  form.content = item.content;
  form.delivery = item.status;
}

function deleteItem(id: number) {
  // delete the item here
  http({
    url: "/posts/" + id,
    method: "delete",
  }).then((r: any) => {
    console.log(r.data);
    loadlist();
  });
}
function onSubmit() {
  http({
    url: "/posts/" + form.id,
    method: "patch",
    data: {
      title: form.title,
      content: form.content,
      status: form.delivery,
    },
  }).then((r: any) => {
    dialogFormVisible.value = false;
    loadlist();
  });
}
</script>

<style lang="scss">
ul {
  width: 300px;

  li {
  list-style: none;
  }
}
</style>
